﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Heaven.Engine.Concurrency
{
    /// <summary>
    /// Special collection designed for concurrent works
    /// </summary>
    public class DeferredCollection<T> : GenericCollection<T>
    {
        #region Fields

        DeferredActions actions = new DeferredActions();

        #endregion

        #region Properties

        /// <summary>
        /// Is the collection changed?
        /// </summary>
        public bool IsChanged
        {
            get { return actions.IsChanged; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Adds an item
        /// </summary>
        /// <param name="item"></param>
        public override void Add(T item)
        {
            actions.Add(AddInternal, item);
        }

        /// <summary>
        /// Removes the given item
        /// </summary>
        /// <param name="item"></param>
        public override void Remove(T item)
        {
            actions.Add(RemoveInternal, item);
        }

        /// <summary>
        /// Performs all deferred actions
        /// </summary>
        public void Perform()
        {
            actions.Perform();
        }

        #endregion

        #region Internal Methods

        /// <summary>
        /// Adds an item
        /// </summary>
        /// <param name="item"></param>
        void AddInternal(object[] item)
        {
            base.Add((T)item[0]);
        }

        /// <summary>
        /// Removes the given item
        /// </summary>
        /// <param name="item"></param>
        void RemoveInternal(object[] item)
        {
            base.Remove((T)item[0]);
        }

        #endregion
    }
}
